package com.yfq.springframework.context;

import com.yfq.springframework.beans.BeansException;
import com.yfq.springframework.beans.config.BeanPostProcessor;

/**
 * @author: yfq
 * @date: 2023/1/31 9:11
 * @description: 处理ApplicationContextAware的BeanPostProcessor
 * 由于在AbstractAutowiredCapableBeanFactory的createBean方法时获取不到ApplicationContext
 * 所以使用这个处理器来携带ApplicationContext后
 * 在bean创建完成后通过执行postProcessBeforeInitialization方法设置applicationContext
 */
public class ApplicationContextAwareProcessor implements BeanPostProcessor {
    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware) {
            ApplicationContextAware aware = (ApplicationContextAware) bean;
            aware.setApplicationContext(applicationContext);
        }

        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
